<template>
  <div class="shishen-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>式神管理</h1>
      <p>管理游戏中的所有式神信息</p>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card card-shadow">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="式神名称" class="form-item">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入式神名称"
            clearable
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="稀有度" class="form-item">
          <el-select v-model="searchForm.rarity" placeholder="请选择稀有度" clearable class="form-select">
            <el-option label="N" value="N" />
            <el-option label="R" value="R" />
            <el-option label="SR" value="SR" />
            <el-option label="SSR" value="SSR" />
            <el-option label="SP" value="SP" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" class="form-item">
          <el-select v-model="searchForm.shishenType" placeholder="请选择类型" clearable class="form-select">
            <el-option label="输出" value="输出" />
            <el-option label="防御" value="防御" />
            <el-option label="辅助" value="辅助" />
          </el-select>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button type="primary" @click="handleSearch" :icon="Search" class="btn-search pulse-hover">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh" class="btn-reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-card class="operation-card card-shadow">
        <el-button type="primary" @click="handleAdd" :icon="Plus" class="btn-add pulse-hover">新增</el-button>
        <el-button 
          type="danger" 
          @click="handleBatchDelete" 
          :disabled="selectedIds.length === 0"
          :icon="Delete"
          class="btn-delete"
        >
          批量删除
        </el-button>
        <div class="selected-info" v-if="selectedIds.length > 0">
          已选择 {{ selectedIds.length }} 项
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <template v-if="loading">
      <TableSkeleton :rowCount="5" />
    </template>
    <template v-else>
      <el-card class="table-card card-shadow">
        <el-table
          :data="tableData"
          @selection-change="handleSelectionChange"
          stripe
          class="data-table"
          :header-cell-style="{backgroundColor: '#f8f9fa'}"
          :row-class-name="rowClassName"
          empty-text="暂无数据"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="60" align="center" />
          <el-table-column prop="name" label="式神名称" width="120" align="center" />
          <el-table-column prop="sex" label="性别" width="80" align="center" />
          <el-table-column prop="rarity" label="稀有度" width="80" align="center">
            <template #default="scope">
              <el-tag 
                :type="getRarityType(scope.row.rarity)"
                size="small"
                class="rarity-tag"
              >
                {{ scope.row.rarity }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="shishenType" label="类型" width="100" align="center" />
          <el-table-column prop="attack" label="攻击" width="80" align="center" sortable />
          <el-table-column prop="basicLife" label="生命" width="80" align="center" sortable />
          <el-table-column prop="defense" label="防御" width="80" align="center" sortable />
          <el-table-column prop="speed" label="速度" width="80" align="center" sortable />
          <el-table-column prop="imageUrl" label="图片" width="100" align="center">
            <template #default="scope">
              <el-image 
                v-if="scope.row.imageUrl"
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
                fit="cover"
                class="shishen-image"
              />
              <div v-else class="shishen-image-empty">
                <el-icon size="24"><Picture /></el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="scope">
              <el-button 
                size="small" 
                @click="handleEdit(scope.row)"
                :icon="Edit"
                class="btn-edit"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row.id)"
                :icon="Delete"
                class="btn-row-delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </el-card>
    </template>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      custom-class="form-dialog"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px"
        class="form-container"
      >
        <el-form-item label="式神名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入式神名称" class="form-input" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别" class="form-select-full">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
            <el-option label="无" value="无" />
          </el-select>
        </el-form-item>
        <el-form-item label="稀有度" prop="rarity">
          <el-select v-model="form.rarity" placeholder="请选择稀有度" class="form-select-full">
            <el-option label="N" value="N" />
            <el-option label="R" value="R" />
            <el-option label="SR" value="SR" />
            <el-option label="SSR" value="SSR" />
            <el-option label="SP" value="SP" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="shishenType">
          <el-select v-model="form.shishenType" placeholder="请选择类型" class="form-select-full">
            <el-option label="输出" value="输出" />
            <el-option label="防御" value="防御" />
            <el-option label="辅助" value="辅助" />
          </el-select>
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <el-input v-model="form.imageUrl" placeholder="请输入图片URL" class="form-input" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入式神简介"
            class="form-textarea"
          />
        </el-form-item>
        <el-form-item label="攻击" prop="attack">
          <el-input-number v-model="form.attack" :min="0" class="form-input-number" />
        </el-form-item>
        <el-form-item label="生命" prop="basicLife">
          <el-input-number v-model="form.basicLife" :min="0" class="form-input-number" />
        </el-form-item>
        <el-form-item label="防御" prop="defense">
          <el-input-number v-model="form.defense" :min="0" class="form-input-number" />
        </el-form-item>
        <el-form-item label="速度" prop="speed">
          <el-input-number v-model="form.speed" :min="0" :step="0.1" class="form-input-number" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false" class="btn-cancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" class="btn-confirm pulse-hover">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Refresh, Plus, Delete, Edit, Picture 
} from '@element-plus/icons-vue'
import { shishenApi } from '../api/shishen.js'
import TableSkeleton from '../components/TableSkeleton.vue'

const loading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()

const searchForm = reactive({
  name: '',
  rarity: '',
  shishenType: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const form = reactive({
  id: null,
  name: '',
  sex: '',
  rarity: '',
  shishenType: '',
  imageUrl: '',
  description: '',
  attack: 0,
  basicLife: 0,
  defense: 0,
  speed: 0,
  criticalHit: 0,
  criticalDamage: 0,
  effectHit: 0,
  effectResistance: 0,
  competenceId: null
})

const rules = {
  name: [{ required: true, message: '请输入式神名称', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  rarity: [{ required: true, message: '请选择稀有度', trigger: 'change' }],
  shishenType: [{ required: true, message: '请选择类型', trigger: 'change' }],
  attack: [{ required: true, message: '请输入攻击值', trigger: 'blur' }],
  basicLife: [{ required: true, message: '请输入生命值', trigger: 'blur' }],
  defense: [{ required: true, message: '请输入防御值', trigger: 'blur' }],
  speed: [{ required: true, message: '请输入速度值', trigger: 'blur' }]
}

// 获取稀有度标签类型
const getRarityType = (rarity) => {
  const types = {
    'N': 'info',
    'R': '',
    'SR': 'warning',
    'SSR': 'success',
    'SP': 'danger'
  }
  return types[rarity] || ''
}

// 行样式
const rowClassName = ({ row }) => {
  // 可以根据稀有度设置不同的行样式
  if (row.rarity === 'SSR' || row.rarity === 'SP') {
    return 'highlight-row'
  }
  return ''
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    // 获取所有数据，不进行分页
    const response = await shishenApi.getAll()
    tableData.value = response
    pagination.total = response.length
  } catch (error) {
    ElMessage.error('数据加载失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = async () => {
  try {
    loading.value = true
    const response = await shishenApi.search(searchForm)
    tableData.value = response
    pagination.total = response.length
  } catch (error) {
    ElMessage.error('搜索失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  searchForm.rarity = ''
  searchForm.shishenType = ''
  pagination.current = 1
  loadData()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增式神'
  Object.assign(form, {
    id: null,
    name: '',
    sex: '',
    rarity: '',
    shishenType: '',
    imageUrl: '',
    description: '',
    attack: 0,
    basicLife: 0,
    defense: 0,
    speed: 0,
    criticalHit: 0,
    criticalDamage: 0,
    effectHit: 0,
    effectResistance: 0,
    competenceId: null
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑式神'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await shishenApi.delete(id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条数据吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await shishenApi.batchDelete(selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (form.id) {
      await shishenApi.update(form)
      ElMessage.success('更新成功')
    } else {
      await shishenApi.create(form)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    if (error.errors) {
      ElMessage.warning('请完善表单信息')
    } else {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.shishen-container {
  padding: 0;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-light-color);
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: var(--text-primary);
  font-weight: 600;
}

.page-header p {
  margin: 0;
  font-size: 14px;
  color: var(--text-secondary);
}

/* 搜索区域 */
.search-card {
  margin-bottom: 24px;
  background-color: var(--card-bg-color);
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
}

.form-item {
  margin-bottom: 0;
}

.form-input {
  width: 200px;
  transition: all 0.3s ease;
}

.form-select {
  width: 120px;
  transition: all 0.3s ease;
}

.btn-search {
  margin-right: 12px;
}

/* 操作区域 */
.operation-area {
  margin-bottom: 24px;
}

.operation-card {
  background-color: var(--card-bg-color);
}

.selected-info {
  display: inline-block;
  margin-left: 20px;
  font-size: 14px;
  color: var(--primary-color);
}

/* 表格区域 */
.table-card {
  background-color: var(--card-bg-color);
}

.data-table {
  margin-bottom: 16px;
}

.data-table .el-table__header th {
  font-weight: 600;
  background-color: #f8f9fa !important;
}

.highlight-row {
  background-color: #f5f7ff !important;
}

.rarity-tag {
  font-size: 12px;
  padding: 2px 8px;
}

.shishen-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.shishen-image:hover {
  transform: scale(1.1);
  box-shadow: var(--box-shadow);
}

.shishen-image-empty {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: var(--text-placeholder);
}

.btn-edit {
  margin-right: 8px;
}

/* 分页 */
.pagination {
  margin-top: 16px;
  text-align: right;
}

/* 对话框 */
.form-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.form-container {
  padding: 0 8px;
}

.form-select-full {
  width: 100%;
  transition: all 0.3s ease;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-input-number {
  width: 100%;
}

/* 通用样式 */
.card-shadow {
  transition: all 0.3s ease;
}

.card-shadow:hover {
  box-shadow: var(--box-shadow);
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .search-form {
    flex-wrap: wrap;
  }
  
  .form-input {
    width: 180px;
  }
}

@media screen and (max-width: 768px) {
  .page-header h1 {
    font-size: 20px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .form-input, .form-select {
    width: 100%;
  }
  
  .operation-card {
    text-align: center;
  }
  
  .selected-info {
    display: block;
    margin-top: 12px;
    margin-left: 0;
  }
  
  .table-card {
    overflow-x: auto;
  }
}
</style>